//router.ts
import { createRouter,createWebHashHistory} from "vue-router"
import store from '../store'



const routers = [
    // { path: "/", props: {msg:'Hello Vue 3 + TypeScript + Vite'},
    // component: () => import('../components/HelloWorld.vue')},
    { path: "/", redirect:"/home"},
    { path: "/home", name:'home', component: () => import('../components/index.vue')},
    { path: "/svrNodeEdit", name:'svrNodeEdit', component: () => import('../components/svrNodeEdit.vue')},
    
]

export const dynamicRoutes = [
    {   path:'/dynamic', name:'dynamic', 
        component: () => import('../components/index.vue'), 
        meta: {
            title: '', 
            icon: ''
        },
        children: []
    }
]

const router = createRouter({
    history: createWebHashHistory(),  // hash 模式，想要改为history 模式可以使用createWebHistory
    routes: routers
})

const comp = import.meta.glob(`../components/*.vue`);
const packageRouter = function (list){
    list.forEach(item => {
        if (item.children?.length) {
            item.component = () => import ('../components/childView.vue')
            packageRouter(item.children)
        } else {
            item.component =  comp[`${item.component}`]
            // item.component = () => import ('../components/HelloWorld.vue')
        }
    })
}

let registerRouteFresh = true
router.beforeEach(async (to, from, next) => {
	// 重定向
    if(to.path == '/home'){
        next()
    } else if (registerRouteFresh) {
        const dyRts = await store.dispatch("generateRoutes")
        packageRouter(dyRts.children)
        router.addRoute(dyRts)
        next({ ...to, replace: true })
        registerRouteFresh = false
    } else {
        // 如果已经获取路由信息，直接跳转
        next()
    }
})

export default router